import { defineStore } from 'pinia'
import { reqLogin, reqUserInfo } from '@/api/user/index'
import type { loginForm } from '@/api/user/type'
import type { UserState } from './types/type'

// 引入常量路由
import { constantRoute } from '@/router/routes'

const useUserStore = defineStore('User', {
  state: (): UserState => {
    return {
      token: sessionStorage.getItem('token'),
      menuRoutes: constantRoute,
      username: '',
      avatar: '',
      flag: false,
      camera: false
    }
  },
  actions: {
    handleSetToken(val: string) {
      this.token = val;
    },
    handleSetUsername(val: string) {
      this.username = val;
    },
    handleSetAvatar(val: string) {
      this.avatar = val;
    },
    handleSetFlag(val: boolean) {
      this.flag = val
    },
    handleSetCamera(val: boolean) {
      this.camera = val
    },
    // 用户登陆方法（弃用）
    async userLogin(data: loginForm) {
      const result: any = await reqLogin(data)
      if (result.code == '200') {
        this.token = result.data.token
        sessionStorage.setItem('token', result.data.token)
        return 'success'
      } else {
        return Promise.reject(new Error(result.data?.message))
      }
    },
    // 获取用户信息
    async userInfo(data: any) {
      const result: any = await reqUserInfo(data)
      if (result.code == '200') {
        this.username = result.data.username
        this.avatar = result.data.avatar
        return 'success'
      } else {
        return Promise.reject('获取用户信息失败')
      }
    }
  },
  getters: {

  }
})

export default useUserStore